#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

struct ListNode 
{
    int val;
    struct ListNode* next;
};

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    struct ListNode* cur1 = list1;
    struct ListNode* cur2 = list2;
    struct ListNode* phead, * ptail;
    phead = ptail = NULL;
    if (cur1 == NULL)
        return cur2;
    if (cur2 == NULL)
        return cur1;
    while (cur1 && cur2)
    {
        if (cur1->val < cur2->val)
        {
            if (ptail == NULL)
            {
                phead = ptail = cur1;
            }
            else
            {
                ptail->next = cur1;
                ptail = ptail->next;
            }
            cur1 = cur1->next;
        }
        else  //cur1->val >= cur2->val
        {
            if (ptail == NULL)
            {
                phead = ptail = cur2;
            }
            else
            {
                ptail->next = cur2;
                ptail = ptail->next;
            }
            cur2 = cur2->next;
        }
    }
    if (cur1)
    {
        while (cur1)
        {
            ptail->next = cur1;
            cur1 = cur1->next;
            ptail = ptail->next;
        }
    }
    if (cur2)
    {
        while (cur2)
        {
            ptail->next = cur2;
            cur2 = cur2->next;
            ptail = ptail->next;
        }
    }

    ptail = NULL;
    return phead;
}